import React, { useEffect, useState } from 'react'
import { message, Modal, Space, TreeSelect } from 'antd'
import ProTable from '@ant-design/pro-table'
import { getExamCategory, getExamQuestions } from '@/services/examquestion'
import ProTableConfig from '@/pages/Exam/TestList/ProTableConfig'
import { ProFormSelect } from '@ant-design/pro-form'

const SelectFixed = (props) => {
  const {
    isModalVisible,
    setIsModalVisible,
    setTableListDataSource,
    tableListDataSource,
    actionRef,
    selectOrder,
    selectedRowKeys,
    setSelectedRowKeys,
  } = props
  const [testCategory, setTestCategory] = useState(undefined)
  const [query, setQuery] = useState(undefined)

  useEffect(async () => {
    let type = selectOrder.map(item => {
      return item.value
    }).join(',')

    setQuery(type)

    /** 获取题库分类 **/
    let result = await getExamCategory()

    const treeData = (result || []).map(item => {
      return {
        key: item.id,
        value: item.id,
        title: item.name,
        children: item.children === undefined ? '' : (item.children || []).map(
          (item) => {
            return {
              key: item.id,
              value: item.id,
              title: item.name,
            }
          }),
      }
    })

    setTestCategory(treeData)
  }, [])

  const columns = [
    {
      title: 'ID',
      width: '10%',
      dataIndex: 'id',
      align: 'center',
      search: false,
    },
    {
      title: '创建人',
      width: '15%',
      align: 'center',
      search: false,
      render: (_, record) => [
        <span key={record.id}>{record.user.username}</span>,
      ],
    },
    {
      title: '题干',
      dataIndex: 'content',
      align: 'left',
      search: false,
    },
    {
      title: '分类',
      width: '10%',
      align: 'center',
      search: false,
      render: (_, record) => [
        <span key={record.id}>{record.category.name}</span>,
      ],
    },
    {
      title: '分类名称',
      dataIndex: 'category_id',
      hideInTable: true,
      hideInForm: true,
      valueType: 'select',
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (!!testCategory.length) {
          return (<TreeSelect treeData={testCategory}/>)
        }
      },
    },
    {
      title: '题型',
      dataIndex: 'type',
      hideInForm: true,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        return (
          <ProFormSelect
            width="lg"
            mode="multiple"
            label={null}
            fieldProps={{
              labelInValue: false,
              onChange: value => {
                setQuery(value)
              },
            }}
            request={async () => selectOrder}
          />
        )
      },
      align: 'center',
    },
    {
      title: '使用次数',
      width: '10%',
      align: 'center',
      dataIndex: 'num',
      search: false,
    },
    {
      title: '分数',
      width: '10%',
      align: 'center',
      dataIndex: 'fraction',
      search: false,
    },
  ]

  const handleOk = () => {
    message.success('添加成功')
    actionRef.current?.reload()
    setIsModalVisible(false)
  }

  /**
   * 关闭模态框
   */
  const handleCancel = () => {
    setIsModalVisible(false)
  }

  /**
   * 表单网络请求
   *
   * @param params
   * @returns {Promise<{total, data, success: boolean}>}
   */
  const getFixed = async (params) => {
    params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))
    const response = await getExamQuestions({ ...params, type: query })
    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total,
    }
  }

  return (
    <Modal title="选择固定题目" width="80%" visible={isModalVisible}
           onOk={() => handleOk()} onCancel={() => handleCancel()}>
      <ProTable
        style={{ marginTop: 28 }} columns={columns}
        {...ProTableConfig}
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        rowSelection={{
          selections: ['SELECT_ALL', 'SELECT_INVERT', 'SELECT_NONE'],
          selectedRowKeys,
          onChange: ((keys, selectedRows) => {
            setSelectedRowKeys([...selectedRowKeys, ...keys])
            if (tableListDataSource.length) {
              let newSource = (tableListDataSource.concat(selectedRows)).reduce(
                (cur, next) => {
                  tableListDataSource[next.id]
                    ? ''
                    : tableListDataSource[next.id] = true && cur.push(next)
                  return cur
                }, []).sort((a, b) => {
                return b['id'] - a['id']
              })

              setTableListDataSource(newSource)
            } else {
              setTableListDataSource(selectedRows)
            }
          }),
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (<Space size={24}>
          <span>
            已选 {tableListDataSource.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        </Space>)}
        request={(params) => getFixed(params)}
        rowKey="id"
        scroll={{ x: 1300 }}
        options={false}
        headerTitle="固定题目操作"/>
    </Modal>
  )
}

export default SelectFixed
